﻿using AutoMapper;
using MediatR;
using SmartCity.BasicData.Api.Application.Commond.AreaTree;
using SmartCity.BasicData.Common;
using SmartCity.BasicData.Domain;
using SmartCity.BasicData.Repo;
using System.Collections.Generic;

namespace SmartCity.BasicData.Api.Application.Handler.AreaTree
{
    public class GetAreaTreeHandler : IRequestHandler<GetAreaTreeCommand, ApiResult<List<GetAreaTreeDTO>>>
    {
        private readonly IBaseRepository<AreasModel> areaRepo;
        private readonly IMapper mapper;

        public GetAreaTreeHandler(IBaseRepository<AreasModel> areaRepo,IMapper  mapper)
        {
            this.areaRepo = areaRepo;
            this.mapper = mapper;
        }

        public Task<ApiResult<List<GetAreaTreeDTO>>> Handle(GetAreaTreeCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<GetAreaTreeDTO>> result = new ApiResult<List<GetAreaTreeDTO>>();
            result.Data = GetTree(0);
            result.Code = Common.Menus.EnumResultCode.Success;
            result.Msg = "查询所有区域层级数据成功!";
            return Task.FromResult(result);
        }
        /// <summary>
        /// 递归方法,找到所有的区域层级树
        /// </summary>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public List<GetAreaTreeDTO> GetTree(long parentId) {
            var query = areaRepo.QueryAllAsync().Result.Where(x => x.ParentId == parentId);
            List<GetAreaTreeDTO> areaList = mapper.Map<List<GetAreaTreeDTO>>(query);//用autopmaper

            foreach (var area in areaList) {
                area.Children = GetTree(area.Id);
            }
            return areaList;
        }
    }
}
